package com.efounder.news.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.core.xml.StubObject;
import com.efounder.chat.model.TabMenuClickEvent;
import com.efounder.chat.model.UpdateBadgeViewEvent;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.interfaces.BadgeUtil;
import com.efounder.mobilenews.R;
import com.efounder.news.activity.DetailNewsActivity;
import com.efounder.news.adapter.NewsListAdapter;
import com.efounder.news.bean.NewsListBean;
import com.efounder.news.http.DataParse;
import com.efounder.news.http.NewsRequestManager;
import com.efounder.news.utils.LogUtils;
import com.efounder.news.view.LoadingPage;
import com.efounder.util.AppContext;
import com.efounder.util.ToastUtil;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

@SuppressLint("ValidFragment")
public class NewsListFragment extends BaseFragment {

    private static final String TAG = NewsListFragment.class.getSimpleName();

    private View mView;
    private RecyclerView mRecyclerView;
    private RefreshLayout mRefreshLayout;
    private NewsListAdapter mNewsListAdapter;
    private LoadingPage mLoadingPage;

    private List<NewsListBean> mNewsBeanList;
    //新闻类别Id
    private String mChannelId;

    private int mStartPage = 1;    // 请求数据的起始页数

    public NewsListFragment() {

    }

    public NewsListFragment(StubObject object) {
        Log.e(TAG, "NewsListFragment: " + object);
        Hashtable stubTable = object.getStubTable();
        if (stubTable != null) {
            this.mChannelId = (String) stubTable.get("newstype");
        }
    }

    /**
     * 从外部向fragment中传参数
     *
     * @param tid
     * @return
     */
    public static NewsListFragment newInstance(String tid) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("channelId", tid);
        NewsListFragment fragment = new NewsListFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mChannelId = getArguments().getString("channelId");
        }
        mNewsBeanList = new ArrayList<>();
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        mView = inflater.inflate(R.layout.fragment_news_list, container, false);
        initView();
        EventBus.getDefault().register(this);
        return mView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        NewsRequestManager.getInstance(getActivity()).cannelOkHttpRequest(TAG + mChannelId);
        mLoadingPage = null;

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        requestData();
        downToRefresh();
        pullUpToLoad();
    }

    private void initView() {
        mLoadingPage = (LoadingPage) mView.findViewById(R.id.loading_page);

        mRefreshLayout = (RefreshLayout) mView.findViewById(R.id.refreshLayout_news);
        mRecyclerView = (RecyclerView) mView.findViewById(R.id.iRecyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        showLoadingPage();

        mNewsListAdapter = new NewsListAdapter(getActivity(), mNewsBeanList);
        mRecyclerView.setAdapter(mNewsListAdapter);
        mNewsListAdapter.setOnItemClickListener(new NewsListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                NewsListBean newsListBean = mNewsBeanList.get(position);
//                Intent intent = new Intent(getActivity(), NewsDetailActivity.class);
                Intent intent = new Intent(getActivity(), DetailNewsActivity.class);
                intent.putExtra("listBean", newsListBean);
                getActivity().startActivity(intent);
            }
        });
    }

    //TODO 处理tabmenu 点击(滚动到顶部)
    @Subscribe(threadMode = ThreadMode.MAIN)
    public synchronized void onSolveEvent(TabMenuClickEvent event) {
        if (getArguments() != null) {
            StubObject stubObject = (StubObject) getParentFragment().getArguments().getSerializable("stubObject");
            if (event.isChildPage(stubObject) && !isHidden()) {
                mRefreshLayout.autoRefresh();
            }
        }
    }

    /**
     * 请求网络数据
     */
    private void requestData() {
        //  http://211.87.224.140:8181/NewService/loadNews?showPage=1&pageNum=10
        showLoadingPage();
        Map<String, String> map = new HashMap<>();
        map.put("showPage", "1");
        map.put("pageNum", "10");
//        if (mChannelId != null && !mChannelId.equals("")) {
        if (mChannelId != null) {

            map.put("channel", mChannelId);
        }
        NewsRequestManager.getInstance(getActivity()).requestAsyn(TAG + mChannelId,"loadNews", 0, (HashMap<String, String>) map,
                new NewsRequestManager.ReqCallBack<String>() {
                    @Override
                    public void onReqSuccess(String result) {
                        if (result == null || "".equals(result)) {
                            return;
                        }
                        List<NewsListBean> newsBeanList = DataParse.getNewsList(result);
                        if (newsBeanList != null) {
                            mNewsBeanList.clear();
                            mNewsBeanList.addAll(newsBeanList);
                            mNewsListAdapter.notifyDataSetChanged();
                            showNewsPage();
                        }
                    }

                    @Override
                    public void onReqFailed(String errorMsg) {
                        showErroPage();
                    }
                });

    }

    /**
     * 下拉刷新
     */
    private void downToRefresh() {
        mRefreshLayout.setOnRefreshListener(new com.scwang.smartrefresh.layout.listener.OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                //更新角标状态  只在最新的栏目下  mChannelId = ""
                if ("".equals(mChannelId) || "0007".equals(mChannelId)) {
                    notifyBadgeUtilUpdate();
                }
                mStartPage = 1;
                //  http://211.87.224.140:8181/NewService/loadNews?showPage=1&pageNum=10
                Map<String, String> map = new HashMap<>();
                map.put("showPage", String.valueOf(mStartPage));
                map.put("pageNum", "10");
                if (mChannelId != null) {
                    map.put("channel", mChannelId);
                }
                NewsRequestManager.getInstance(getActivity()).requestAsyn(TAG + mChannelId,"loadNews", 0, (HashMap<String, String>) map, new NewsRequestManager.ReqCallBack<String>() {
                    @Override
                    public void onReqSuccess(String result) {
                        if (result == null || "".equals(result)) {
                            return;
                        }
                        mNewsBeanList.clear();
                        List<NewsListBean> refreshList = DataParse.getNewsList(result);
                        if (refreshList == null || refreshList.size() == 0) {
                            ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_no_data);
                        }
                        mNewsBeanList.addAll(refreshList);
                        mNewsListAdapter.notifyDataSetChanged();
                        mRecyclerView.smoothScrollToPosition(0);
                        refreshLayout.finishRefresh();
                    }

                    @Override
                    public void onReqFailed(String errorMsg) {
//                        Toast.makeText(getActivity(), errorMsg, Toast.LENGTH_SHORT).show();
                        showErroPage();
//                        mIRecyclerView.setRefreshing(false);
                    }
                });
            }


        });


    }

    /**
     * 上拉加载
     */
    private void pullUpToLoad() {

        mRefreshLayout.setOnLoadMoreListener(new com.scwang.smartrefresh.layout.listener.OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                mStartPage += 1;
                //  http://211.87.224.140:8181/NewService/loadNews?showPage=1&pageNum=10
                Map<String, String> map = new HashMap<>();
                map.put("showPage", String.valueOf(mStartPage));
                map.put("pageNum", "10");
                if (mChannelId != null) {
                    map.put("channel", mChannelId);
                }
                NewsRequestManager.getInstance(getActivity()).requestAsyn(TAG + mChannelId,"loadNews", 0, (HashMap<String, String>) map, new NewsRequestManager.ReqCallBack<String>() {
                    @Override
                    public void onReqSuccess(String result) {
                        if (isDetached() || isRemoving()) {
                            return;
                        }
                        LogUtils.d(TAG + mChannelId, result);
                        if (result == null || "".equals(result)) {
                            return;
                        }
                        List<NewsListBean> newlist = DataParse.getNewsList(result);
                        if (newlist == null) {
                            refreshLayout.finishLoadMoreWithNoMoreData();
                            return;
                        }
                        if (newlist.size() == 0) {
                            refreshLayout.finishLoadMoreWithNoMoreData();
//                                mLoadMoreFooterView.setStatus(LoadMoreFooterView.Status.THE_END);
                        } else {
                            mNewsBeanList.addAll(newlist);
                            refreshLayout.finishLoadMore();
//                                mLoadMoreFooterView.setStatus(LoadMoreFooterView.Status.GONE);
                        }
                        mNewsListAdapter.notifyDataSetChanged();
//                            mIRecyclerView.setRefreshing(false);
                    }

                    @Override
                    public void onReqFailed(String errorMsg) {
//                    Toast.makeText(getActivity(), errorMsg, Toast.LENGTH_SHORT).show();
//                            mIRecyclerView.setRefreshing(false);
                        showErroPage();
//                            mLoadMoreFooterView.setStatus(LoadMoreFooterView.Status.ERROR);
                    }
                });
            }
        });


    }


    /**
     * 展示加载页面
     */
    private void showLoadingPage() {
//        mIRecyclerView.setVisibility(View.INVISIBLE);
        if (mLoadingPage != null) {
            mLoadingPage.setLoadingView();
        }
    }

    /**
     * 如果有新闻就展示新闻页面
     */
    private void showNewsPage() {
        if (mLoadingPage != null) {
            mLoadingPage.setSuccessView();
        }


    }

    /**
     * 如果没有网络就展示空消息页面
     */
    private void showEmptyPage() {
//        mIRecyclerView.setVisibility(View.INVISIBLE);
        mLoadingPage.setEmptyView();
    }

    private void showErroPage() {
//        mIRecyclerView.setVisibility(View.INVISIBLE);
        if (mLoadingPage == null) {
            return;
        }
        mLoadingPage.setErrorView();
        mLoadingPage.setLoadingClickListener(new LoadingPage.LoadingClickListener() {
            @Override
            public void clickListener() {
                requestData();
            }
        });
    }


    /**
     * 更新资讯角标的状态
     */
    private void notifyBadgeUtilUpdate() {
        //如果是显示角标的状态，发送通知更新
        if (EnvironmentVariable.getProperty("news_new_message_notify", "0").equals("1")) {
            EnvironmentVariable.setProperty("news_new_message_notify", "0");
            EventBus.getDefault().post(new UpdateBadgeViewEvent(BadgeUtil.CHAT_ID_NEWS + "", (byte) 2));
        }
    }
}
